<?php

namespace app\company\model;

use Exception;

/**
 * @property  int $id
 * @property  string $user_name  用户名
 * @property  string $password 密码
 * @property  string $real_name 负责人(真名)
 * @property  string $is_super 1：超级管理员，2：普通管理员',
 * @property  int $store_id 公司id
 * @property  string $role_id 角色ID
 * @property  int $company_id 公司ID
 * @method  admin()
 * @method  Super($super)
 */
class CompanyUser extends Base
{

    public static function onBeforeInsert(CompanyUser $model): void
    {
        $model->password   = md5($model->password . 'dt');
        $model->is_super   = 2;//超级管理员
        $model->company_id = getCompanyId();
    }

    /**
     * @param CompanyUser $model
     * @return void
     * @throws Exception
     */
    public static function onAfterInsert(CompanyUser $model): void
    {
        self::addRole($model);
    }

    /**
     * @param CompanyUser $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(CompanyUser $model): void
    {
        $model->password = md5($model->password . 'dt');
        self::addRole($model);
    }

    /**
     * @param CompanyUser $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(CompanyUser $model): void
    {
        if ($ids = $model->companyUserRoles()->column('id')) CompanyUserRole::destroy($ids,true);//真实删除
    }


    /**
     * @param $model
     * @return void
     * @throws Exception
     */
    public static function addRole($model): void
    {
        if ($role_ids = request()->param('role_ids', 0)) {
            $arr  = explode(',', $role_ids);
            $data = [];
            foreach ($arr as $v) {
                $array['company_role_id'] = $v;
                $array['company_user_id'] = $model->id;
                $data[]                   = $array;
                //if($model->companyUserRoles()->count())$model->companyUserRoles->delete();当是一对多关系时,返回的是集合,并不是模型,这只能软删除
                if ($ids = $model->companyUserRoles()->column('id')) CompanyUserRole::destroy($ids,true);//真实删除
                (new CompanyUserRole())->saveAll($data);
            }
        }

    }
}